package cn.jd.org.controller;

import cn.jd.basic.anno.PreAuthorize;
import cn.jd.basic.util.AjaxResult;
import cn.jd.basic.util.PageList;
import cn.jd.org.domain.Employee;
import cn.jd.org.query.EmployeeQuery;
import cn.jd.org.service.EmployeeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/emp")
@Api(value = "员工的API",description="员工相关的CRUD功能")
@PreAuthorize
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;
    @PutMapping
    @PreAuthorize(name = "员工数据添加和修改",sn = "employee:addEmployee")
    public AjaxResult addEmployee(@RequestBody Employee employee) {
        try {
            if(employee.getId() == null){
                System.out.println(employee+"我是校验部门的");
                employeeService.save(employee);
                return AjaxResult.me().success();
            }else {
                employeeService.update(employee);
                return AjaxResult.me().success();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return AjaxResult.me().fail();

    }
    @DeleteMapping("/{id}")
    @PreAuthorize(name = "员工根据id删除数据",sn = "employee:deleteEmployee")
    public  AjaxResult deleteEmployee(@PathVariable("id") Long id){

        try {
            employeeService.remove(id);
            return AjaxResult.me().success();
        }catch (Exception e){
            e.printStackTrace();
        }
        return AjaxResult.me().fail();
    }
    @GetMapping
    @ApiOperation(value = "查询所有数据" )
    @PreAuthorize(name = "查询所有员工的数据",sn = "employee:findall")
    public List<Employee> findall(){
        return employeeService.findAll();
    }
    @GetMapping("/{id}")
    @ApiOperation(value = "根据id查询一条数据" )
    @PreAuthorize(name = "根据id查询单个员工",sn = "employee:findById")
    public  Employee findById(@ApiParam(value="传入long类型的数据",required = true) @PathVariable("id") Long id){
        return employeeService.findById(id);
    }
    @PostMapping
    @PreAuthorize(name = "员工的分页查询加高级搜索",sn = "employee:queryByPage")
    public PageList<Employee> queryByPage(@RequestBody EmployeeQuery query){
        return employeeService.queryByPage(query);
    }
    @PatchMapping
    @PreAuthorize(name = "员工批量删除员工",sn = "employee:deleteAll")
    public  AjaxResult deleteAll(@RequestBody List<Long> ids){

        try {
            employeeService.deleteByAll(ids);
            return AjaxResult.me().success();
        }catch (Exception e){
            e.printStackTrace();
        }
        return AjaxResult.me().fail();
    }

}
